package com.bjpowernode.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Objects;

public class Util {

    private static final String tempDir;

    static {
        String userDir = System.getProperty("user.dir");
        if (userDir.endsWith("/"))
            tempDir = userDir + "temp";
        else
            tempDir = userDir + "/temp";
        File temp = new File(tempDir);
        if (!temp.exists())
            temp.mkdirs();
    }

    public static String getTempDir() {
        return tempDir;
    }

    public static boolean strEquals(String str,String... matchStr){
        Objects.requireNonNull(matchStr);
        for (String match : matchStr) {
            if (match.equals(str))
                return true;
        }
        return false;
    }

    public static FileItem getFile(HttpServletRequest request, String pname) {
        if (!ServletFileUpload.isMultipartContent(request)) {
            return null;
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> formItems=null;
        try {
            formItems = upload.parseRequest(request);
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        }
        if (formItems != null && formItems.size() > 0) {
            // 迭代表单数据
            for (FileItem item : formItems) {
                // 处理不在表单中的字段
                if (!item.isFormField()) {
                    if (item.getFieldName().equals(pname))
                        return item;
                }
            }
        }
        return null;
    }
}
